/*
 * Semaphore Demo
 * Liu Jinzhu
 * 2018-04-10
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREAD 	6

void *thread_function(void *arg);

int main() {

    int res;                						// 保存线程创建返回值
    pthread_t threads[NUM_THREAD];    			// 保存线程
    void *thread_result;   	 					// 线程运行返回值
    int lots_of_thread;

    for (lots_of_thread = 0; lots_of_thread < NUM_THREAD; lots_of_thread++) {
    	res = pthread_create(&(threads[lots_of_thread]), NULL, thread_function, (void *)(&lots_of_thread));
    	if (0 != res) {
    		perror("线程创建失败\n");
    	   exit(EXIT_FAILURE);
    	}
    	sleep(1);
    }

    printf("等待线程结束...\n");
    for (lots_of_thread = NUM_THREAD; lots_of_thread >= 0; lots_of_thread--) {
    	res = pthread_join(threads[lots_of_thread], &thread_result);
      if (0 == res) {
    	  printf("结束一个线程\n");
      } else {
    	  perror("等待线程结束失败\n");
        }
     }

    printf("线程全部结束\n");
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
	int my_number = *((int *)arg);
	int rand_num;
	printf("线程函数已运行,参赛为:%d\n", my_number);
	rand_num = 1 + (int)(0.9 * rand() / (RAND_MAX + 1.0));
	sleep(rand_num);
	printf("第%d个线程结束\n", my_number);
   pthread_exit(NULL);
}

